﻿var subs, zxList, tmList = [];



    //判断是否登录，若未登录则跳转到登录页


//类别切换
$('#nav li').click(function () {
    var _this = $(this);
    if (_this.hasClass('cur')) {
        return;
    }

    $('#nav .cur').removeClass('cur');
    _this.addClass('cur');

    //清除所有定时器
    for (var i = 0; i < tmList.length; i++) {
        if (tmList[i]) {
            clearTimeout(tmList[i]);
        }
    }
    tmList = [];

    var exchCode = $(this).data('exchcode');
    var name = $(this).data('name');
    var html = '', item;
    if (!exchCode) {
        //自选
        buildHtml(zxList);
        fnZx();

        //自选编辑按钮
        $('#panel').append('<a href="zx.html" class="btnZx">+</a>');
    } else {
        subs = list[name];
        buildHtml(subs);
        GeRefreshData(exchCode);
    }
});


if (uid) {
    //用户登录，获取自选列表
    ld();
    $.ajax({
        url: 'http://hej1.shqlkj.com/api/zxlist?uid=' + uid,
        dataType: 'jsonp',
        jsonp: "callback",
        success: function (json) {
            lc();
            if (json.code == 0) {
                //服务端返回错误信息
                alert(decodeURIComponent(json.data));
                saveZx(defaultZxList);
            } else if (json.code == 100) {
                //若登录用户未自选过，则显示默认自选
                saveZx(defaultZxList);
            } else if (json.code == 200) {
                //显示用户自选(只有SYMBOL_CODE)，从本地js中寻找其他字段
                var tmpList = [], item, isFind = false;
                try {
                    json.data.name = JSON.parse(json.data.name);
                    for (var i = 0; i < json.data.name.length; i++) {
                        isFind = false;
                        item = json.data.name[i];
                        for (var key in list) {
                            if (list[key]) {
                                for (var k = 0; k < list[key].length; k++) {
                                    if (item == list[key][k].SYMBOL_CODE) {
                                        tmpList.push(list[key][k]);
                                        isFind = true;
                                        break;
                                    }
                                }
                            }
                            if (isFind) {
                                break;
                            }
                        }
                    }
                    saveZx(tmpList);
                } catch (e) {
                    alert('服务端返回的自选数据格式错误：' + json.data.name);
                    //自选编辑按钮
                    $('#panel').append('<a href="zx.html" class="btnZx">+</a>');
                }
                
            }
        },
        error: function (e) {
            lc();
            alert('获取用户自选数据失败，显示默认自选列表');
            saveZx(defaultZxList);
        }
    });
} else {
    //非登录用户，直接显示默认自选
    saveZx(defaultZxList);
}

function saveZx(data) {
    zxList = data;
    //缓存到sessionStorage中，供其他页面使用，关闭页面失效
    sessionStorage.setItem('zxList', JSON.stringify(zxList));
    $('#nav li').eq(0).click();
}

//黄金
ckhq('WGJS', 'XAU', 2);
//白银
ckhq('WGJS', 'XAG', 2);
//美元
ckhq('WH', 'USD', 2);
//原油
ckhq('NYMEX', 'CONC', 2);

//参考行情
function ckhq(exchCode, symbolCode, decimal) {
    setTimeout(function () {
        $.ajax({
            url: symbol + "?exchName=" + exchCode + "&symbol=" + encodeURIComponent(symbolCode) + "&st=" + Math.random(),
            dataType: 'jsonp',
            jsonp: "callback",
            success: function (data) {
                var el = $('#hq_' + symbolCode),
                p2 = el.find('.p2'),
                p3 = el.find('.p3'),
                dif;

                if (data.o.length == 0) {
                    p2.html('暂无数据');
                    p3.html('');
                } else {
                    //有变更才更新
                    if (data.c[0] != p2.html()) {
                        dif = toFixed((data.c[0] - data.p[0]), decimal);

                        p2.html(toFixed(data.c[0], decimal));
                        p3.html(dif + ',' + changeRate(data.c[0], data.p[0]) + '%');
                        if (dif > 0) {
                            p2.addClass('red').removeClass('green');
                            p3.addClass('red').removeClass('green');
                        } else if (dif < 0) {
                            p2.addClass('green').removeClass('red');
                            p3.addClass('green').removeClass('red');
                        }
                    }
                }
                ckhq(exchCode, symbolCode, decimal);
            }
        });
    }, sxtime)
}



//非自选刷新
function GeRefreshData(exchCode) {
    //定时刷新数据
    var tmp = setTimeout(function () {
        $.ajax({
            url: quotes + '?exchName=' + exchCode + '&st=' + Math.random(),
            dataType: 'jsonp',
            jsonp: "callback",
            success: function (data) {
                $('#panel .item_hq').each(function () {
                    var _this = $(this),
                        _id = _this[0].id,
                        p2 = _this.find('.p2'),
                        p3 = _this.find('.p3'),
                        item, dif;

                    if (_id == 'CONC') {
                        //若是原油，则从参考行情里面获取数据
                        var tmp = $('#hq_CONC');
                        p2[0].outerHTML = tmp.find('.p2')[0].outerHTML;
                        p3[0].outerHTML = tmp.find('.p3')[0].outerHTML;
                    } else {
                        for (var i = 0; i < data.i.length; i++) {
                            item = data.i[i];
                            if (item == _id) {
                                //先判断当前价是否变更再操作DOM，提升性能
                                if (data.c[i] != p2.html()) {
                                    var decimal = getDecimal(subs[_this.data('i')].PRICE_SCALE);
                                    dif = toFixed((data.c[i] - data.p[i]), decimal);

                                    p2.html(toFixed(data.c[i], decimal));
                                    p3.html(dif + ',' + changeRate(data.c[i], data.p[i]) + '%');
                                    if (dif > 0) {
                                        p2.addClass('red').removeClass('green');
                                        p3.addClass('red').removeClass('green');
                                    } else if (dif < 0) {
                                        p2.addClass('green').removeClass('red');
                                        p3.addClass('green').removeClass('red');
                                    }
                                }
                                break;
                            } else {
                                continue;
                            }
                        }
                    }
                });

                GeRefreshData();
            }
        });
    }, sxtime);
    tmList.push(tmp);
}

//创建自选刷新
function fnZx() {
    var item;
    for (var i = 0; i < zxList.length; i++) {
        item = zxList[i];
        refreshZx(symbol + "?exchName=" + item.EXCH_CODE + "&symbol=" + encodeURIComponent(item.SYMBOL_CODE) + "&st=" + Math.random(), $('#panel .' + item.SYMBOL_CODE), getDecimal(item.PRICE_SCALE));
    }
}

//自选刷新
function refreshZx(url, el, decimal) {
    var tmp = setTimeout(function () {
        $.ajax({
            url: url,
            dataType: 'jsonp',
            jsonp: "callback",
            success: function (data) {
                var p2 = el.find('.p2'),
                    p3 = el.find('.p3'),
                    dif;

                if (data.o.length == 0) {
                    p2.html('暂无数据');
                    p3.html('');
                } else {
                    //有变更才更新
                    if (data.c[0] != p2.html()) {
                        dif = toFixed((data.c[0] - data.p[0]), decimal);

                        p2.html(toFixed(data.c[0], decimal));
                        p3.html(dif + ',' + changeRate(data.c[0], data.p[0]) + '%');
                        if (dif > 0) {
                            p2.addClass('red').removeClass('green');
                            p3.addClass('red').removeClass('green');
                        } else if (dif < 0) {
                            p2.addClass('green').removeClass('red');
                            p3.addClass('green').removeClass('red');
                        }
                    }
                }

                refreshZx(url, el, decimal);
            }
        });
    }, sxtime);
    tmList.push(tmp);
}

//填充行情
function buildHtml(data) {
    var html = '', item;
    for (var i = 0; i < data.length; i++) {
        item = data[i];
        html += '<a class="item_hq ' + item.SYMBOL_CODE + '" href="hq.html?exchCode=' + item.EXCH_CODE + '&symbolCode=' + item.SYMBOL_CODE + '&codeType=' + item.codeType + '&name=' + item.SYMBOL_NAME + '&scale=' + item.PRICE_SCALE + '" id="' + item.SYMBOL_CODE + '" data-i="' + i + '">' +
                    '<p class="p1">' + item.SYMBOL_NAME + '</p>' +
                    '<p class="p2">...</p>' +
                    '<p class="p3">...</p>' +
                '</a>';
    }
    $('#panel').html(html);
}